package com.cyy.view.search

import cn.hutool.core.util.StrUtil
import com.cyy.model.GmodelModel
import com.jfinal.kit.Kv
import com.jfinal.plugin.activerecord.Db
import javafx.geometry.Orientation
import javafx.stage.FileChooser
import tornadofx.*
import tornadofx.controlsfx.listSelectionView
import java.io.File

class SearchLeft : View("My View") {
    val gm: GmodelModel by inject()

    val slp = listProperty<String>(gm.columns)
    val tlp = listProperty<String>("")
    val wbtmpl = stringProperty()
    override val root = vbox {
        form {
            // 这种实现方式比较简洁
            listSelectionView(slp, tlp) {
                slp.clear()
                tlp.clear()
                orientation = Orientation.VERTICAL
            }
            button("...") {
                action {
                    val projectPath = gm.curProjectPath.value

                    val efset = arrayOf(FileChooser.ExtensionFilter("选择模板文件", "*.*"))

                    val fnset = chooseFile("选择模板文件", efset, FileChooserMode.Single) {
                        // p初始目录为当前项目目录
                        initialDirectory = File(projectPath)
                    }
                    if (fnset.isNotEmpty()) {
                        wbtmpl.value = "${fnset.first()}"
                    }
                }
            }
            textfield(wbtmpl) {
                text = "${gm.curProjectPath.value}/doc/tmpl/view/index.html"
            }
            buttonbar {

                button("Search").action {
                    //                    val sql = "select ${selectedCol.value} from ${gm.leftTable.value}"
                    val kv=Kv.create()
                    var cols = StrUtil.join(",", tlp.value)
                    if (cols.isNullOrBlank()) {
                        cols = "*"
                        tlp.value = gm.columns
                    }
//                    println(cols)
                    val sql = "select ${cols} from ${gm.leftTable.value}"
                    runAsync {
                        val ret = Db.use().find(sql)
//                    println(ret)
                        kv.set("ret", ret).set("cols", tlp.value).set("title", gm.leftTable.value)
                    } ui { success ->
                        gm.tplStringOut.value = gm.engine.value.getTemplate(wbtmpl.value).renderToString(kv)

                    }
                }
            }
        }
    }
}
